#include "SocketConnector.h"

SocketConnector::SocketConnector()
  : debug_(false) { }

SocketConnector::SocketConnector(InetAddress &addr)
  : debug_(false)
{
  this->open(addr);
}

SocketConnector::~SocketConnector()
{
  close( handle_ );
}

void SocketConnector::open (const InetAddress &addr)
{
  addrinfo hints;
  addrinfo *lookups;

  memset(&hints, 0, sizeof hints);

  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;

  if (getaddrinfo(addr.getIp().c_str(), addr.getPort().c_str(), &hints, &lookups) != 0 )
    std::cout << "Couldnt get addrinfo";
  
  addrinfo * p;
  for (p = lookups; p != NULL; p = p->ai_next)
    {
      if (debug_) std::cout << "Trying new addrinfo struct\n";
      
      if (p->ai_family != AF_INET)
	{
	  if (debug_) std::cout << "Addrinfo isnt ipv4\n";
	  continue;
	}

      if ( (handle_ = socket(p->ai_family, p->ai_socktype, p->ai_protocol )) == -1 )
	{
	  if (debug_) std::cout << "Socket failed\n";
	  continue;
	}

      if ( connect( handle_, p->ai_addr, p->ai_addrlen) == -1)
	{
	  if (debug_) std::cout << "Connect failed\n";
	  close(handle_);
	  continue;
	}

      if (debug_) std::cout << "Found addrinfo\n";

      break;
    }

  if (p == NULL && debug_)
    std::cout << "Failed to find addrinfo\n";
    

  freeaddrinfo(lookups);
  
  if (debug_) std::cout << "connector ready\n";
}

void SocketConnector::setStream(SocketStream &ss)
{
  ss.setHandle( handle_ );
}




